package com.usian.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.behavior.dtos.FollowBehaviorDto;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.UserRelationDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserFan;
import com.usian.model.user.pojos.ApUserFollow;
import com.usian.user.feign.ApAuthorFeign;
import com.usian.user.mapper.ApUserFollowMapper;
import com.usian.user.service.ApUserFanService;
import com.usian.user.service.ApUserFollowService;
import com.usian.user.service.ApUserLoginService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserFollowServiceImpl extends ServiceImpl<ApUserFollowMapper, ApUserFollow>
        implements ApUserFollowService {

    @Autowired
    ApAuthorFeign apAuthorFeign;
    @Autowired
    ApUserFanService apUserFanService;
    @Autowired
    ApUserLoginService apUserLoginService;

    @Autowired
    KafkaTemplate kafkaTemplate;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        if (dto==null || dto.getArticleId()==null ||dto.getOperation()==null ||dto.getAuthorId()==null){
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询作者信息
        ApAuthor apAuthor = apAuthorFeign.findById(dto.getAuthorId());

        if (apAuthor!=null){
            //关注 0   取消关注1
            ApUser apUser = AppThreadLocalUtils.getUser();
            Integer userId = null;
            if (apUser!=null){
                userId = apUser.getId();
            }
            if (dto.getOperation()==0){
                //关注
                follows(userId,dto.getAuthorId(),apAuthor.getName(),dto.getArticleId());
            }else if (dto.getOperation()==1){
                //取消关注
                Nofollows(userId,dto.getAuthorId(),apAuthor.getName());
            }

        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void Nofollows(Integer userId, Integer followId, String name) {

        //删除 ApUserFollow表中的信息
        this.remove(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, userId)
                .eq(ApUserFollow::getFollowId, followId));

        //删除 ApUserFan表中的信息
        apUserFanService.remove(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getFansId, userId)
                .eq(ApUserFan::getUserId, followId));
    }

    private void follows(Integer userId, Integer followId,String followName,Long articleId) {

        //查询是否已关注 ，否则添加信息
        ApUserFollow apUserFollow = this.getOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, userId)
                .eq(ApUserFollow::getFollowId, followId));
        if (apUserFollow==null){

            ApUserFollow apUserFollow1 = new ApUserFollow();
            apUserFollow1.setUserId(userId);
            apUserFollow1.setFollowId(followId);
            apUserFollow1.setFollowName(followName);
            apUserFollow1.setCreatedTime(new Date());
            apUserFollow1.setIsNotice(true);
            apUserFollow1.setLevel((short)1);
            this.save(apUserFollow1);

            ApUserFan apUserFan = apUserFanService.getOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getFansId, userId)
                    .eq(ApUserFan::getUserId, followId));

            if (apUserFan==null){
                apUserFan = new ApUserFan();
                apUserFan.setUserId(followId);
                apUserFan.setFansId(userId.longValue());
                ApUser apUser = apUserLoginService.getById(userId);
                if (apUser!=null){
                    apUserFan.setFansName(apUser.getName());
                }
                apUserFan.setLevel((short)0);
                apUserFan.setIsDisplay(true);
                apUserFan.setIsShieldLetter(false);
                apUserFan.setIsShieldComment(false);
                apUserFan.setCreatedTime(new Date());
                apUserFanService.save(apUserFan);
            }

            //关注完毕，记录用户关注的行为  Kafka发消息
            FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
            followBehaviorDto.setUserId(userId);
            followBehaviorDto.setArticleId(articleId);
            followBehaviorDto.setFollowId(followId);

            kafkaTemplate.send("followBehavior", JSON.toJSONString(followBehaviorDto));
            System.out.println("用户关注行为发送消息："+JSON.toJSONString(followBehaviorDto));
        }
    }
}
